package com.chengxiaoxiao.libarypartner.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.chengxiaoxiao.libarypartner.R;
import com.chengxiaoxiao.libarypartner.constants.AppConsrants;
import com.chengxiaoxiao.libarypartner.domain.Books;
import com.chengxiaoxiao.libarypartner.utils.ApiAddress;
import com.chengxiaoxiao.libarypartner.utils.LoadDialogUtils;
import com.chengxiaoxiao.libarypartner.utils.ToastUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.image.SmartImageView;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends Activity
{
    private ListView listBooks;
    private EditText editSearch;
    private List<Books> listBook;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        editSearch = (EditText)findViewById(R.id.editSearch);
        listBooks = (ListView) findViewById(R.id.listBooks);

        editSearch.setFocusable(true);
        editSearch.setFocusableInTouchMode(true);
        editSearch.requestFocus();
        editSearch.requestFocusFromTouch();

    }

    public void search(View v)
    {
        String search = editSearch.getText().toString();

        if(search.length()<=0)
        {
            ToastUtils.makeText(SearchActivity.this,"请输入搜索内容");
            return;
        }




        loadBooks(search);
        listBooks.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                Intent intent = new Intent(SearchActivity.this, BookActivity.class);

                intent.putExtra(AppConsrants.BOOK_ID,listBook.get(position).getId()+"");
                startActivity(intent);
            }
        });

    }

    private void loadBooks(String search)
    {


        LoadDialogUtils.show(SearchActivity.this,"","加载中...");

        final AsyncHttpClient client = new AsyncHttpClient();
        client.get(ApiAddress.getApiDomain() + "/client/ClientServlet?op=search&bookName="+search, new AsyncHttpResponseHandler()
        {
            @Override
            public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody)
            {
                LoadDialogUtils.hidden();
                String body = new String(responseBody);
                try
                {
                    JSONArray jsonArray = new JSONArray(body);

                    listBook = new ArrayList<Books>();

                    for (int i = 0; i < jsonArray.length(); i++)
                    {

                        JSONObject jsonObj = jsonArray.getJSONObject(i);


                        long id = jsonObj.getInt("id");
                        String bookName = jsonObj.getString("bookName");
                        String author = jsonObj.getString("author");
                        String categoryName = jsonObj.getString("categoryName");
                        String imagesPath = jsonObj.getString("imagesPath");
                        String publisherName = jsonObj.getString("publisherName");
                        long number = jsonObj.getInt("number");

                        String address = jsonObj.getString("address");
                        Books book = new Books(id, bookName, author, categoryName, imagesPath, number, address, publisherName);
                        listBook.add(book);
                    }

                    listBooks.setAdapter(new MyHotAdapter());


                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
            {
                LoadDialogUtils.hidden();
                ToastUtils.makeText(SearchActivity.this, "网络连接错误");
            }
        });
    }
    class MyHotAdapter extends BaseAdapter
    {

        @Override
        public int getCount()
        {
            return listBook.size();

        }

        @Override
        public Object getItem(int position)
        {
            return listBook.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View view;
            if (convertView == null)
            {
                view = View.inflate(SearchActivity.this, R.layout.list_item_category_books, null);
            } else
            {
                view = convertView;
            }

            SmartImageView imageIcon = (SmartImageView) view.findViewById(R.id.ivIcon);
            TextView textName = (TextView) view.findViewById(R.id.textName);
            TextView textAuthor = (TextView) view.findViewById(R.id.textAuthor);
            TextView textPublisher = (TextView) view.findViewById(R.id.textPublisher);
            TextView textNumber = (TextView) view.findViewById(R.id.textNumber);
            TextView textAddress = (TextView) view.findViewById(R.id.textAddress);

            Books item = listBook.get(position);


            textName.setText(item.getBookName());
            textAuthor.setText("作者："+item.getAuthor());
            textPublisher.setText("出版社："+item.getCategoryName());
            textNumber.setText("数量："+item.getNumber() + "");
            textAddress.setText(item.getAddress());
            imageIcon.setImageUrl(item.getImagesPath());


            return view;
        }
    }
}
